﻿using UnityEngine;
using System.Collections;

public class scStageManager : MonoBehaviour
{
	public Sprite stageOpenedSprite;
	

	// Use this for initialization
	void Start()
	{
		PlayerPrefs.DeleteAll();
		for (int i=1; i <= 1; i++)
		{
			scPlayerInfo.SaveLevelOpened(i);
		}

		_MakeStageBoxes();
	}

	// Update is called once per frame
	void Update()
	{
	}

	void _MakeStageBoxes()
	{
		const float stageHorizonCriteria = 1 / 22f;		// viewpoint x
		const float stageVerticalCriteria = 1 / 16f;	// viewpoint y
		float stageVerticalCount = 16f;

		int stageLevel = 1;
		for (int vertCount = 0; vertCount < 3; ++vertCount)
		{
			stageVerticalCount -= 3f;

			for (float stageHorizonCount = 2f; stageHorizonCount < 22f; stageHorizonCount += 3f)
			{
				_SelectLevelBoxOpenedorLocked(
					stageLevel++,
					new Vector3(stageHorizonCount * stageHorizonCriteria, stageVerticalCount * stageVerticalCriteria, 0.0f)
					);
			}
		}
	}

	void _SelectLevelBoxOpenedorLocked(int level, Vector3 targetViewPos)
	{
		Vector3 targetScreenPos;

		if (scPlayerInfo.IsLevelOpened(level))
		{
			targetScreenPos = Camera.main.ViewportToWorldPoint(targetViewPos);
			targetScreenPos.z = 0;

			GameObject stageBox = (GameObject)Instantiate(
				Resources.Load("Prefabs/StageBoxes/pfStageOpened"),
				targetScreenPos,
				Quaternion.Euler(0f, 0f, 0f)
				);

			stageBox.GetComponent<SpriteRenderer>().sprite = stageOpenedSprite;

			targetViewPos.y += 0.02f;
			GUIText levelGuiText = stageBox.GetComponentInChildren<GUIText>();
			levelGuiText.text = level.ToString();
			levelGuiText.transform.position = targetViewPos;

			stageBox.SendMessage("InitStars", level, SendMessageOptions.DontRequireReceiver);
		}
		else
		{
			targetViewPos.y += 0.01f;
			targetScreenPos = Camera.main.ViewportToWorldPoint(targetViewPos);
			targetScreenPos.z = 0;

			Instantiate(
				Resources.Load("Prefabs/StageBoxes/pfStageLocked"),
				targetScreenPos,
				Quaternion.Euler(0f, 0f, 0f)
				);
		}
	}
}
